package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result showTypeList() {
        String key = "shop:type";
        //从redis中查数据
        String shopType = stringRedisTemplate.opsForValue().get(key);
        //存在直接返回
        if (StrUtil.isNotBlank(shopType)){
            //转为list<ShopType>集合
            List<ShopType> shopList = JSONUtil.toList(shopType, ShopType.class);
            return Result.ok(shopList);
        }
        //不存在，从数据库查数据
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        //不存在，返回错误
        if (shopTypeList.isEmpty()){
            return Result.fail("未查找到类型信息");
        }
        //存在，写入redis,设置有效时间
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shopTypeList),30, TimeUnit.MINUTES);
        //返回
        return Result.ok(shopTypeList);
    }
}
